package zdh.jfinabbsapp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;

import java.util.ArrayList;
import java.util.List;

import zdh.jfinabbsapp.R;
import zdh.jfinabbsapp.api.API;
import zdh.jfinabbsapp.api.dao.GeneralTopic;
import zdh.jfinabbsapp.api.dao.Section;
import zdh.jfinabbsapp.util.Session;
import zdh.jfinabbsapp.widget.GeneralTopicListFragment;

/**
 * 作者：zdh1000
 * 创建时间： 2015/6/28 12:08
 * 邮箱：wdzdh1000@163.com
 */
//测试连接,zdh1000
public class MainActivity extends AppCompatActivity {
    private ListView leftItem;//左边菜单
    private DrawerLayout drawerLayout;
    private Toolbar toolbar;
    private ActionBarDrawerToggle drawerToggle;//箭头

    private String[] leftMenus = {"首页", "资讯", "问答", "博客", "退出"};
    private int curItem = 0;
    private boolean isOpenDraw = false;
    private boolean isLogin = false;

    private ImageView imageView;
    private TextView loginText;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                Log.d("Handler", "handleMessage");
                Log.d("Handler", "handleMessage:" + leftMenus.length);
                leftMenus = API.getAllSections(Session.getSectionList());
                leftItem.setAdapter(new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, leftMenus));
                leftItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        drawerLayout.closeDrawers();
                        if (position == curItem)
                            return;
                        else {
                            display(position);
                            curItem = position;
                        }
                    }
                });
                curItem = 0;
                display(0);
            } else if (msg.what == 1) {
                isLogin = true;
                Log.d("MainActivity", "token:" + Session.getUser().getToken());
                loginText.setText(Session.getUser().getNickname());
                KJBitmap kjb = new KJBitmap();
                kjb.display(imageView, Session.getUser().getAvatar());
//                imageView.setImageDrawable();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //设置状态栏透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        init();


    }

    private void init() {

        //获取drawerlayout
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main_drawerlayout);
        //获取toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        //获取leftItem
        leftItem = (ListView) findViewById(R.id.activity_main_left_menu);
        //设置toolbar背景颜色
        toolbar.setBackgroundColor(getResources().getColor(R.color.background_toolbar));
        //设置toolbar的标题
        toolbar.setTitle(R.string.app_name);
        //设置toolbar的标题颜色，默认
        toolbar.setTitleTextColor(Color.WHITE);
        //把activity原有的actionbar替换成toolbar
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        //初始化drawerToggle对象，实为一个监听器
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                R.string.draw_open, R.string.draw_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                isOpenDraw = true;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                isOpenDraw = false;
            }

        };
        //同步状态
        drawerToggle.syncState();
        drawerLayout.setDrawerListener(drawerToggle);

        new Thread() {
            @Override
            public void run() {
                super.run();
                List<Section> list = new ArrayList<>();
                String url = API.getAllSectionsUrl();
                if (Session.isAutoUpdate()) {
                    Log.d("MainActivity", "自动更新，从网络获取数据.");
                    //线程获取栏目，并初始化leftItem
                    API.http.get(url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String t) {
                            super.onSuccess(t);
                            Session.setSectionList(API.getAllSections(t));
                            Log.d("Thread", "Thread:" + Session.getSectionList().size());
                            Log.d("Thread", "Thread:" + leftMenus.length);
                            handler.sendEmptyMessage(0);
                        }
                    });

                } else {
                    Log.d("MainActivity", "从本地获取数据.");
                    String temp = new String(API.http.getCache(url));
                    list = API.getAllSections(temp);
                    if(list.size()==0||list == null)
                    {
                        Log.d("MainActivity", "从网络获取数据.");
                        //线程获取栏目，并初始化leftItem
                        API.http.get(url, new HttpCallBack() {
                            @Override
                            public void onSuccess(String t) {
                                super.onSuccess(t);
                                Session.setSectionList(API.getAllSections(t));
                                Log.d("Thread", "Thread:" + Session.getSectionList().size());
                                Log.d("Thread", "Thread:" + leftMenus.length);
                                handler.sendEmptyMessage(0);
                            }
                        });
                    }
                    handler.sendEmptyMessage(0);
                }

            }
        }.start();

        imageView = (ImageView) findViewById(R.id.activity_main_imageview);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawers();
                if(!isLogin)
                {
                    drawerLayout.closeDrawers();

                    openScanner();
                }
                else
                {
                    Toast.makeText(MainActivity.this, "已登录", Toast.LENGTH_LONG).show();
                }


            }
        });


        loginText = (TextView) findViewById(R.id.activity_main_loginText);

        login("");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /* 返回键 */
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isOpenDraw) {
                drawerLayout.closeDrawers();
            } else {
                finish();
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        //https://github.com/journeyapps/zxing-android-embedded
        if (id == R.id.scanner) {
//            openScanner();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        final IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        Log.d("token", result.getContents());
        Toast.makeText(this, "token:" + result.getContents(), Toast.LENGTH_LONG).show();
        login(result.getContents());
    }

    private void login(final String token) {
        //获取用户具体信息
        new Thread() {
            @Override
            public void run() {
                super.run();
                String url = API.getUserUrl();
                if (token.equals("") || API.checkCache(url) || !Session.isAutoUpdate()) {
                    Log.d("MainActivity", "load user from cache.");
                    String temp = new String(API.http.getCache(url));
                    Session.setUser(API.getUserByToken(temp));
                    handler.sendEmptyMessage(1);
                } else {
                    Log.d("MainActivity", "load user from network.");
                    HttpParams params = new HttpParams();
//                    Log.d("MainActivity", "token:"+result.getContents());
                    params.put("token", API.doToken(token));
                    //线程获取user
                    API.http.post(url, params, new HttpCallBack() {
                        @Override
                        public void onSuccess(String t) {
                            super.onSuccess(t);
                            Session.setUser(API.getUserByToken(t));
                            handler.sendEmptyMessage(1);
                        }
                    });
                    //下载头像
                    //API.http.download()
                }


            }
        }.start();
        //result即为扫描结果，result.getContents（） 返回图书的ISBN码。
    }

    private void display(int position) {
        Fragment fragment = null;
//        if(!DeviceInfo.isNetworkAvailable(this))
//        {
//            Toast.makeText(this,"无有效的网络连接",Toast.LENGTH_LONG).show();
//        }
        curItem = position;
        Bundle b = new Bundle();
        b.putString("tab", Session.getSectionList().get(position).getTab());
        fragment = GeneralTopicListFragment.instance(b);
//        switch (position){
//            case 0:
//                curItem = 0;
////                toolbar.setTitle(leftMenus[position]);
//
//        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.activity_main_content, fragment)
                    .commitAllowingStateLoss();
        }

        leftItem.setItemChecked(position, true);
        leftItem.setSelection(position);
        drawerLayout.closeDrawers();
    }

    private void openScanner() {
        IntentIntegrator intentIntegrator = new IntentIntegrator(this); // `this` is the current Activity
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        intentIntegrator.setOrientationLocked(true);
        intentIntegrator.setPrompt("Scan a barcode");
//            intentIntegrator.setCameraId(0);  // Use a specific camera of the device
        intentIntegrator.setBeepEnabled(false);
        intentIntegrator.initiateScan();
//            intentIntegrator.getMoreExtras().get(Intents.Scan.RESULT);
//            Intent intent = new Intent(this, CaptureActivity.class);
//            startActivity(intent);
    }
}
